<!DOCTYPE html>
<style>
  body {
    height: 10000px;
    width: 10000px;
  }
</style>

<body></body>
<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<script type="text/javascript">
  'use strict';

  async_test(function(t) {
    history.scrollRestoration = 'auto';
    window.scrollTo(0, 0);

    // create history entries and then verify the impact of scrollRestoration 
    // when they are popped
    var entries = {
      /* TODO: spec does not defines behavior of 'auto' so we should not expect scroll position for these */
      '#1': {type: 'push',    expectedScroll: [50, 100],  scrollRestoration: 'auto'},
      '#2': {type: 'replace', expectedScroll: [100, 200], scrollRestoration: 'auto'},
      /* Scroll position should not be restored for these. */
      '#3': {type: 'push',    expectedScroll: [555, 555], scrollRestoration: 'manual'},
      '#4': {type: 'replace', expectedScroll: [555, 555], scrollRestoration: 'manual'}
    };

    // setup entries
    for (var key in entries) {
      var entry = entries[key],
        beforeValue = history.scrollRestoration,
        newValue = entry.scrollRestoration;

      var args = [{key: key}, '', key];
      if (entry.type == 'push') {
        history.pushState.apply(history, args);
      } else {
        history.pushState(null, '', key);
        history.replaceState.apply(history, args);
      }
      assert_equals(history.scrollRestoration, beforeValue, `${entry.type} retain current history.scrollRestoration value`);
      history.scrollRestoration = newValue;
      assert_equals(history.scrollRestoration, newValue, `Setting scrollRestoration to ${newValue} does expected`);
      window.scrollBy(50, 100);
    }

    // setup verification
    window.addEventListener('hashchange', t.step_func(function() {
      var key = location.hash,
        entry = entries[key];

      if (key === '') {
        t.done();
        return;
      }
      console.log(`verifying ${key}`);
      assert_equals(history.state.key, key, `state should have key: ${key}`);
      assert_equals(document.scrollingElement.scrollLeft, entry.expectedScroll[0], `scrollLeft is correct for ${key}`);
      assert_equals(document.scrollingElement.scrollTop, entry.expectedScroll[1], `scrollTop is correct ${key}`);

      window.history.back();
    }));

    // reset the scroll and kick off the verification
    setTimeout(function() {
      history.pushState(null, null, '#done');
      window.scrollTo(555, 555);
      window.history.back();
    }, 0);

  }, 'history.{push,replace}State retain and respect history.scrollRestoration');
</script>
